package com.payment.notify;

import java.util.concurrent.DelayQueue;

import javax.jms.Queue;

import org.apache.activemq.command.ActiveMQQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.jms.annotation.EnableJms;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import com.payment.notify.core.NotifyPersist;
import com.payment.notify.core.NotifyQueue;
import com.payment.notify.core.NotifyTask;
import com.payment.notify.service.NotifySerivce;

@SpringBootApplication(exclude = DataSourceAutoConfiguration.class) //不使用默认的数据源
@EnableJms
public class PaymentAppNotifyApplication {
	
private static Logger logger = LoggerFactory.getLogger(PaymentAppNotifyApplication.class);
	
	public static DelayQueue<NotifyTask> tasks = new DelayQueue<NotifyTask>();

	private static ThreadPoolTaskExecutor threadPool;

	private static NotifyQueue notifyQueue;
	
	private static NotifySerivce notifySerivce;
	
	public static NotifyPersist notifyPersist;
	
	@Bean
	public Queue queue() {
		return new ActiveMQQueue("notify.queue");
	}

	public static void main(String[] args) {
		ApplicationContext applicationContex = SpringApplication.run(PaymentAppNotifyApplication.class, args);
		System.out.println("applicationContex=="+applicationContex);
		threadPool = (ThreadPoolTaskExecutor) applicationContex.getBean("threadPool");
		System.out.println("threadPool=="+threadPool);
		notifyQueue = applicationContex.getBean(NotifyQueue.class);
//		System.out.println("notifyQueue=="+notifyQueue);
		notifySerivce = applicationContex.getBean(NotifySerivce.class);
		System.out.println("notifySerivce=="+notifySerivce);
		notifyPersist = applicationContex.getBean(NotifyPersist.class);
		System.out.println("notifyPersist=="+notifyPersist);
		startInitFromDB();
		startThread();
	}
	
	private static void startThread() {
		threadPool.execute(new Runnable() {
			public void run() {
				try {
					while (true) {
						 Thread.sleep(50);//50毫秒执行一次
						// 如果当前活动线程等于最大线程，那么不执行
						if (threadPool.getActiveCount() < threadPool.getMaxPoolSize()) {
							final NotifyTask task = tasks.poll();
							if (task != null) {
								threadPool.execute(new Runnable() {
									public void run() {
										System.out.println(threadPool.getActiveCount() + "---------");
										tasks.remove(task);
										task.run();
									}
								});
							}
						}
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * 从数据库中取一次数据用来当系统启动时初始化
	 */
	private static void startInitFromDB() {
		notifySerivce.startInitFromDB(notifyQueue);
	}
}
